package com.itheima.tliaswebmanagement.aspect;

import com.itheima.tliaswebmanagement.mapper.OperateLogMapper;
import com.itheima.tliaswebmanagement.pojo.entity.OperateLog;
import com.itheima.tliaswebmanagement.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.aspectj.lang.ProceedingJoinPoint;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @Description LogAspect
 * @Author ziguan ling
 * @Date 2025--01--13
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {
    private final OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.tliaswebmanagement.anno.LogOperator)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        log.info("开始重要操作日志记录");

        OperateLog operateLog = new OperateLog();

        //2.封装数据4
        //操作人ID(登录人id)
        operateLog.setOperateEmpId(getCurrentLoginId());
        //操作时间(系统当前时间)
        operateLog.setOperateTime(LocalDateTime.now());
        //操作类名，语法：pjp.getTarget().getClass().getName();
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        //操作方法名:pjp.getSignature().getName()
        operateLog.setMethodName(pjp.getSignature().getName());
        //操作方法参数:pjp.getArgs()得到一个数组，转换为字符串
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
        //定义执行开始毫秒数
        Long start = System.currentTimeMillis();
        //执行原有方法
        Object result = pjp.proceed();
        //操作方法返回值
        operateLog.setReturnValue(result == null ? null : result.toString());
        //定义执行结束毫秒数
        Long end = System.currentTimeMillis();
        //操作耗时（结束毫秒数-开始毫秒数）
        operateLog.setCostTime(end - start);

        //3.调用日志mapper执行插入数据
        operateLogMapper.insert(operateLog);


        return result;
    }

    //获取当前登录员工id
    private Integer getCurrentLoginId() {
        //打印当前线程id
        System.out.println("LogAspect: 当前线程id=" + Thread.currentThread().getId());
        return ThreadLocalUtil.getLoginId();

    }
}
